#include <iostream>
#include <sys/socket.h>
#include <cstdlib>
#include <cstring>
#include <arpa/inet.h>

#define SERVER_PORT 9999
#define BUFFER_SIZE 128

int main()
{
    // 创建套接字的句柄
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1)
    {
        perror("socket error");
        exit(-1);
    }

    // 绑定IP和端口信息
    struct sockaddr_in localAddress;

    // 清空结构体的脏数据
    memset(&localAddress, 0, sizeof(localAddress));

    // 地址族是IPV4
    localAddress.sin_family = AF_INET;
    localAddress.sin_port = htons(SERVER_PORT);

    // 设置全通规则
    localAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    // 绑定
    bind(sockfd, reinterpret_cast<const struct sockaddr *>(&localAddress), sizeof(localAddress));

    char buffer[BUFFER_SIZE] = {0};
    while (1)
    {
        recvfrom(sockfd, buffer, sizeof(buffer), 0, NULL, NULL);

        std::cout << "buffer:" << buffer << std::endl;

        // 清除脏数据
        memset(buffer, 0, sizeof(buffer));
    }

    return 0;
}